<?php
/**
 * LICENSE
 *
 * This source file is subject to the new BSD license that is bundled
 * with this package in the file license.txt or that can be found at 
 * http://code.google.com/p/billboardce/wiki/License.
 *
 * @package    Slide_Stream_Map
 * @category   Model
 * @license    http://code.google.com/p/billboardce/wiki/License New BSD License
 * @version    SVN: $Id: $
 */
class Slidestream_Slide extends Ot_Db_Table
{
    /**
     * Name of the table in the database
     *
     * @var string
     */
    protected $_name = 'tbl_slidestream_slide';
  
    /**
     * Primary key of the table
     *
     * @var string
     */
    protected $_primary = 'slidestreamSlideId';
    
    /**
     * Returns an array of all the slides & slidestreams that are in a given 
     * slide stream ID
     * 
     * @param int $slidestreamId The slide stream ID to get the entities for
     * @param bool $getDisabled Whether or not to return disabled slides
     * @return array The entities in the slide stream
     */
    public function getEntitiesForSlidestream($slidestreamId, $getDisabled = false) {
        
        $where = $this->getAdapter()->quoteInto('slidestreamId = ?', $slidestreamId);
        
        if ($getDisabled == false) {
            $where .= ' AND '
                    . $this->getAdapter()->quoteInto('enabled = ?', 1);
        }
        
        $entities = $this->fetchAll($where, 'order DESC')->toArray();
        
        $entityList = array();
        
        $slide = new Slide();
        $slidestream = new Slidestream();
        $slidePlugin = new Slide_Plugin();
        $slidestreamPlugin = new Slidestream_Plugin();
        
        $slidePlugins = $slidePlugin->getEnabledPlugins();
        $slidestreamPlugins = $slidestreamPlugin->getEnabledPlugins();
        
        $slideIds = array();
        
        foreach ($entities as $e) {
            $slideIds[] = $e['entityTypeId'];
        }
        
        $slideDataMap = array();
        $where = $slide->getAdapter()->quoteInto('slideId IN(?)', $slideIds);
        $slideData = $slide->fetchAll($where)->toArray();
        
        foreach ($slideData as $s) {
            $slideDataMap[$s['slideId']] = $s;
        }
        
        $returnData = array();
        
        $screenshotPath = realpath(APPLICATION_PATH . '/../public/screenshots');
            
        foreach ($entities as $e) {
            
            $tmpData = null;
            
            $thumbnailPath = 'images/slideThumbDefault.png';
            $previewPath = 'images/slidePreviewDefault.png';
            
            if (isset($slideDataMap[$e['entityTypeId']])) {
                
                $tmpData = $slideDataMap[$e['entityTypeId']];
                
                if (file_exists($screenshotPath . '/' . $e['entityTypeId'] . '/preview.jpg')) {
                    $thumbnailPath = 'screenshots/' . $e['entityTypeId'] . '/thumbnail.jpg';
                    $previewPath = 'screenshots/' . $e['entityTypeId'] . '/preview.jpg';
                }
                
            }
            
            if (!is_null($tmpData)) {
                
                $e['data'] = $tmpData;
                
                $e['data']['thumbnailPath'] = $thumbnailPath;
                $e['data']['previewPath'] = $previewPath;
                
                $e['pluginData'] = array();
            
                foreach ($slidePlugins as $p) {
                    
                    $e['pluginData'][$p['name']] = $p['object']->find($e['entityTypeId']);
                    
                    if (is_null($e['pluginData'][$p['name']])) {
                        $e['pluginData'][$p['name']] = array();
                    }
                }
                
                $typeObj = Slidetype::factory($e['data']['slideType']);
                
                $e['typeData'] = $typeObj->find($e['entityTypeId']);
                
                if (is_null($e['typeData'])) {
                    $e['typeData'] = array();
                }
                
                $entityList[] = $e;
            }
        }
        
        $returnData['slides'] = $entityList;
        $returnData['slidestreamPlugins'] = array();
        $returnData['slidestreamInfo'] = $slidestream->find($slidestreamId)->toArray();

        foreach ($slidestreamPlugins as $p) {
            
            $returnData['slidestreamPlugins'][$p['name']] = $p['object']->find($slidestreamId);
            
            if (is_null($returnData['slidestreamPlugins'][$p['name']])) {
                $returnData['slidestreamPlugins'][$p['name']] = array();
            }
        }
        
        return $returnData;
    }
    
    
    /**
     * Saves the data for a slidestream.  The data is a keyed array of slides like:
     * 
     * slideId       => 56
     * order         => 1
     * url           => http://www.yahoo.com
     * title         => Yahoo
     * displayLength => 5
     * 
     * @param int $slidestreamId The slide stream ID to save
     * @param array The array of slides to saves
     */
    public function saveSlidestream($slidestreamId, $data)
    {
        $slide = new Slide();
        $slidestream = new Slidestream();
        
        $db = $this->getAdapter();
        
        $db->beginTransaction();

        // just remove all the existing slidestream-slide mappings
        // since we're going to add the current view back
        $where = $db->quoteInto('slidestreamId = ?', $slidestreamId);
        try {
            $this->delete($where);   
        } catch (Exception $e) {
            $db->rollBack();
            throw new Ot_Exception_Data('Error saving slidestream data. ' . $e->getMessage());
        }
        
        $slidestreamData = array(
                            'slidestreamId'   => $slidestreamId,
                            'title'           => $data['slidestreamInfo']['title'],
                            'updateTimestamp' => time()
                           );
                           
        try {
            $slidestream->update($slidestreamData, null);
        } catch (Exception $e) {
            $db->rollBack();
            throw new Ot_Exception_Data('Error saving slidestream data. ' . $e->getMessage());
        }
        
        $slidestreamPlugin = new Slidestream_Plugin();
        $slidestreamPlugins = $slidestreamPlugin->getEnabledPlugins();
        
        foreach ($data['slides'] as $d) {
            
            $slideMapData = array(
                                'slidestreamId' => $slidestreamId,
                                'entityType'    => 'slide',
                                'entityTypeId'  => $d['slideId'],
                                'order'         => $d['order'],
                                'displayLength' => $d['displayLength'],
                                'enabled'       => $d['enabled'],
                                'toggleOpen'    => $d['toggleOpen'],
                            );

            // insert the mappings back                
            try {
                $this->insert($slideMapData, $where);
            } catch (Exception $e) {
                $db->rollBack();
                throw new Ot_Exception_Data('Error saving slidestream mapping. ' . $e->getMessage());
            }

        }
        
        // save slidestream plugin data
        foreach ($slidestreamPlugins as $p) {
            if (isset($data['slidestreamPluginData'][$p['name']]) && !empty($data['slidestreamPluginData'][$p['name']])) {                
                
                try {
                    $p['object']->saveConfigurationForm($slidestreamId, $data['slidestreamPluginData'][$p['name']]);
                }
                catch (Exception $e) {
                    $db->rollBack();
                    throw new Ot_Exception_Data('Error saving slidestream plugin data. ' . $e->getMessage());
                }
            }
        }
        
        $db->commit();
    }
}